﻿@COFE ?= {}

utils = COFE.utils
$ = jQuery

nullGuid = "00000000-0000-0000-0000-000000000000"

class SigninApp extends Spine.Controller
  constructor : ->
    super  

  elements : 
    ".signin" : "btnSignin"
    ".refresh" : "btnRefresh"
    "#signinform" : "frmSignin"

  events : 
    "click .signin" : "OnSignIn"
    "click .signout" : "OnSignOut"
     
  init : ->
    if utils.getCookie("cofews_signature") isnt ""
      @refresh()  


  callUrl : (url, crediential, successFunc, errorFunc) ->    
    params = { 
      type : "POST" 
      url : url
      success : successFunc
      error : errorFunc
      }

    if (crediential isnt undefined)
      params.data = crediential    
    $.ajax(params)  


  OnSignIn : =>
    crediential = $("#signin_form").serialize();
    @signin(crediential)    

  OnSignOut : =>
    @signout

  signout : =>
    @callUrl(COFE.signoutUrl, "", 
    (data, textStatus, jqXHR) =>           
      @App.trigger("signedOut", "Signout")
    (data, textStatus, jqXHR) =>
      utils.showMessage(jqXHR, "Logout failed")
    )

  signin : (crediential) =>    
    @callUrl(COFE.signinUrl, crediential, 
    (data, textStatus, jqXHR) =>       
      @App.trigger("signedIn", "Signin")
    (data, textStatus, jqXHR) =>
      errorStr = (if (jqXHR is "Not Found")
      then ("Wrong login or password.")
      else ("Cannot connect to the server."))
      utils.showMessage(errorStr, "Login failed")
    )
  
  refresh : =>
    @callUrl(COFE.signinUrl, "", 
    (data, textStatus, jqXHR) =>       
      @App.trigger("signedIn", "Signin")
    (data, textStatus, jqXHR) =>       
      console.log "Refresh failed, signin required."
      ) 

COFE.Signin = SigninApp

